package com.itheima.aspect;

import com.alibaba.fastjson.JSON;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * Author: Zheng
 * Date:   2024/1/29  11:41
 * Package：com.itheima.aspect
 * Description：
 * Version：1.0
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.itheima.annotation.MyLog)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        OperateLog operateLog = new OperateLog();

        //设置操作人id
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        operateLog.setOperateUser((Integer) claims.get("id"));
        //设置操作时间
        operateLog.setOperateTime(LocalDateTime.now());
        //设置执行的全类名
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        //获取执行方法名
        operateLog.setMethodName(joinPoint.getSignature().getName());
        //获取方法运行参数
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        //获取方法执行开始时间
        long begin = System.currentTimeMillis();
        //执行原始方法
        Object object = joinPoint.proceed();
        //或方法执行结束时间
        long end = System.currentTimeMillis();
        //设置方法执行耗时
        operateLog.setCostTime(end-begin);

        //设置方法返回值
        operateLog.setReturnValue(JSON.toJSONString(object));

        //执行日志新增方法
        operateLogMapper.insert(operateLog);

        return object;
    }
}
